package com.hsurosy.hsuchain.nft.base.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClient;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * RestClient工具类
 *
 * @Author Hsu琛君珩
 * @Date 2024-10-04 18:56
 * @Description
 * @Version: v1.0.0
 */
@Slf4j
public class RestClientUtils {

    /**
     * 配置HTTP请求头
     *
     * @param headers 请求头对象
     * @param headersMap 请求头键值对
     * @return 配置好的请求头
     */
    public static HttpHeaders configureHeaders(HttpHeaders headers, Map<String, String> headersMap) {
        headersMap.forEach((k, v) -> headers.add(k.toString(), v.toString()));
        return headers;
    }

    /**
     * 构建带查询参数的URL
     *
     * @param path 请求路径
     * @param querys 查询参数
     * @return 完整的URL
     * @throws UnsupportedEncodingException 编码异常
     */
    private static String buildUrl(String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (querys != null) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (sbQuery.length() > 0) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                } else if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=").append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (sbQuery.length() > 0) {
                sbUrl.append("?").append(sbQuery);
            }
        }
        return sbUrl.toString();
    }

    /**
     * 发送POST请求
     *
     * @param host 主机地址
     * @param path 请求路径
     * @param headersMap 请求头
     * @param querys 查询参数
     * @param bodys 请求体
     * @return 响应实体
     * @throws Exception 异常处理
     */
    public static ResponseEntity<?> doPost(String host, String path, Map<String, String> headersMap,
                                           Map<String, String> querys, Map<String, String> bodys) throws Exception {

        RestClient restClient = RestClient.builder()
                .baseUrl(host)
                .build();

        var result = restClient.post()
                .uri(buildUrl(path, querys))
                .headers(headers -> configureHeaders(headers, headersMap))
                .body(bodys)
                .retrieve()
                .onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
                    log.error("HTTP客户端错误，请求: {}, 响应: {}", request, response);
                }).onStatus(HttpStatusCode::is5xxServerError, (request, response) -> {
                    log.error("HTTP服务端错误，请求: {}, 响应: {}", request, response);
                }).toBodilessEntity();

        return result;
    }
}
